/**
 * Created by haowanh5 on 2016/11/1.
 */

"use strict";

const Util = require("util");
const Vector = require("../Utils/Vector");

const Logger = require("pomelo-logger").getLogger("UserHandler", __filename);

const Player = require("./PlayerClass");
const GameObject = require("./GameObject");

function UserHandler(gameServer, collisionHandler, gameObjectHandler) {
    /**
     * PlayerTracker List
     *
     * @type {Array}
     */
    this.toUpdate = [];

    this.gameServer = gameServer;
    this.collisionHandler = collisionHandler;
    this.gameObjectHandler = gameObjectHandler;
}

module.exports = UserHandler;

UserHandler.TYPE = GameObject.TYPE_PLAYER;

UserHandler.prototype.update = function () {
    var time = new Date();
    while (this.toUpdate.length > 0) {
        var client = this.toUpdate[0];
        this.toUpdate.shift();
        if (!client || client.fullyDisconnected) continue;

        if (client.player !== null) {
            // calc client visible and nonVisible nodes
            client.update();
        }

        setTimeout(function () {
            if (this.fullyDisconnected) return;
            // console.log("PlayerId: [ %s ] [ %s ]", this.playerID, this.fullyDisconnected);
            this.gameServer.userHandler.toUpdate.push(this);
        }.bind(client), 40);
    }

    this.gameServer.tickUserHandler = new Date() - time;
};

/**
 * Add Connected Client Into An Array
 * @param client
 */
UserHandler.prototype.addClient = function (client) {
    this.toUpdate.push(client.playerTracker);
    this.gameServer.gameObjectHandler.toUpdate.push(client.playerTracker);
};

/**
 * Create PlayerObject
 * @param {PlayerTracker} player
 * @param {Vector} pos
 * @returns {Player}
 */
UserHandler.prototype.onPlayerSpawn = function (player, pos) {
    // Todo: Need To Specify Player Static Id
    return new Player(this.gameServer.getNewObjectId(), player, pos, this.gameServer, "11900001");
};

/**
 * Random A Pos In The Map Area
 * @returns {Vector}
 */
UserHandler.prototype.getRandomPos = function () {
    var xSum = this.gameServer.config.borderRight - this.gameServer.config.borderLeft;
    var ySum = this.gameServer.config.borderBottom - this.gameServer.config.borderTop;
    return new Vector(
        Math.floor(Math.random() * xSum + this.gameServer.config.borderLeft),
        Math.floor(Math.random() * ySum + this.gameServer.config.borderTop)
    );
};
